<template>
  <div class="my-records">
    <div class="header">
      <h2>我的考试记录</h2>
    </div>

    <el-empty v-if="items.length === 0 && !loading" description="暂无记录" />

    <div class="ka-grid" v-loading="loading">
      <div class="ka-card" v-for="row in items" :key="row.id">
        <div class="content">
          <span class="ka-badge">尝试 {{ row.attemptNumber }}</span>
          <h3 style="margin:8px 0 6px;">{{ row.examTitle || '考试' }}</h3>
          <p class="text-muted" style="margin:0 0 8px;">{{ row.totalScore }} / {{ row.totalPoints }} · {{ formatDuration(row.timeSpent) }}</p>
          <div style="display:flex; justify-content:space-between; align-items:center;">
            <small class="text-muted">提交于 {{ row.submitTime }}</small>
            <div>
              <el-button size="small" type="primary" @click="view(row.id)" style="margin-right:6px;">查看结果</el-button>
              <el-button size="small" @click="retake(row.examId)">再次参加</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="pager">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="load"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { examApi } from '@/api/exam'
import { getErrorMessage } from '@/api/http'

const loading = ref(false)
const items = ref<any[]>([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const load = async () => {
  try {
    loading.value = true
    const res = await examApi.getMyRecords({ page: page.value, pageSize: pageSize.value })
    items.value = res.content || []
    total.value = res.totalElements || 0
  } catch (e: any) {
    console.error(e)
    ElMessage.error(getErrorMessage(e))
  } finally {
    loading.value = false
  }
}

const view = (recordId: number) => {
  // 保留路由栈与状态
  window.location.href = `/exam-result/${recordId}`
}

const retake = (examId: number) => {
  window.location.href = `/exam/${examId}`
}

const formatDuration = (seconds: number) => {
  if (!seconds) return '0秒'
  const m = Math.floor(seconds / 60)
  const s = seconds % 60
  return m ? `${m}分${s}秒` : `${s}秒`
}

onMounted(load)
</script>

<style scoped>
.my-records { padding: 20px; }
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.title { font-weight: 600; }
.sub { color: #909399; font-size: 12px; }
.pager { margin-top: 16px; text-align: center; }
</style>


